import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { BasicService } from '../../../../@core/data/basic.service';
import { ServerDataSource } from 'ng2-smart-table';
// 消息提醒
import { ToasterConfig } from 'angular2-toaster';
import { NotificationsService } from '../../../../@core/utils/notifications.service';
import { FroalaComponent } from '../../../../@theme/components/index';
const api = 'achievements';
@Component({
  selector: 'ngx-achievement-modal',
  templateUrl: './achievement.modal.component.html',
})
export class AchievementModalComponent implements OnInit {

  @Input() modalHeader: string;
  @Input() isEdit: boolean;
  @Input() achievementId: number;
  @Input() achievement: any;
  @Input() source: ServerDataSource;

  statusType: any[];
  userList: any[];
  courseList: any[];
  qbankList: any[];
  paperList: any[];

  constructor(private activeModal: NgbActiveModal, private basicService: BasicService, private notificationsService: NotificationsService) {
  }

  ngOnInit() {
    // 初始化下拉框的数据
    this.basicService.getOne('configs/findByCtype?ctype=status_type')
      .subscribe((data: any) => {
        this.statusType = data.rows;
      });
    this.basicService.getOne('users/findAll')
      .subscribe((data: any) => {
        this.userList = data.rows;
      });
    this.basicService.getOne('courses/findAll')
      .subscribe((data: any) => {
        this.courseList = data.rows;
      });
    this.basicService.getOne('qbanks/findAll')
      .subscribe((data: any) => {
        this.qbankList = data.rows;
      });
    this.basicService.getOne('papers/findAll')
      .subscribe((data: any) => {
        this.paperList = data.rows;
      });
  }
  // 取消
  closeModal() {
    this.activeModal.close();
  }

  // 保存
  saveData() {
    if (this.isEdit) {
      this.basicService.update(api, this.achievement).subscribe(
        data => {
          this.notificationsService.showToast('success', '操作', '<b>更新 <em>成功！</em></b>');
          this.activeModal.close();
          this.source.refresh();
        },
        err => {
          this.notificationsService.showToast('error', '操作', '<b>更新 <em>失败！</em></b>');
          console.error('Error saving!');
        },
      );
    } else {
      this.basicService.create(api, this.achievement).subscribe(
        data => {
          this.notificationsService.showToast('success', '操作', '<b>保存 <em>成功！</em></b>');
          this.activeModal.close();
          this.source.refresh();
        },
        err => {
          this.notificationsService.showToast('error', '操作', '<b>保存 <em>失败！</em></b>');
          console.error('Error saving!');
        },
      );
    }
  }


}
